import { NexusServiceClient } from '@/utils/nexus_grpc_web_pb.js';
import { EmptyRequest, Network, Networks, GetPathRequest } from '@/utils/nexus_pb';

var client = new NexusServiceClient('http://localhost:8080', null, null);

function ipToInt(ip) {  
  const octets = ip.split('.');  
  if (octets.length !== 4) {  
      throw new Error('Invalid IP address');  
  }  
    
  const a = parseInt(octets[0], 10) << 24;  
  const b = parseInt(octets[1], 10) << 16;  
  const c = parseInt(octets[2], 10) << 8;  
  const d = parseInt(octets[3], 10);  
    
  return a | b | c | d;  
} 

export async function getNetworks(
  params: {},
  options?: { [key: string]: any },
) {
  return new Promise((resolve, reject) => {
    var req = new EmptyRequest();

    client.getNetworks(req, {}, (err, resp: Networks) => {
      if (err) {
        reject(err);
      } else {
        resolve(resp.toObject().networksList);
      }
    });
  });
}

export async function createNetwork(
  params: { name?: string; token?: string },
  options?: { [key: string]: any },
) {
  return new Promise((resolve, reject) => {
    var req = new Network();
    req.setName(params.name);
    req.setToken(params.token);

    client.createNetwork(req, {}, (err, resp) => {
      if (err) {
        reject(err);
      } else {
        resolve(resp);
      }
    });
  });
}

export async function protoGetPath(
  params: { network?: string; src?: string; dip: number },
  options?: { [key: string]: any },
) {
  return new Promise((resolve, reject) => {
    var req = new GetPathRequest();
    req.setNetwork(params.network);
    req.setSource(params.src);
    req.setDip(ipToInt(params.dip));
    console.log(req);

    client.getPath(req, {}, (err, resp) => {
      if (err) {
        reject(err);
      } else {
        console.log(resp);
        resolve(resp);
      }
    });
  });
}
